<template>
    <action-bar :actionBarData="actionBarData" @search="searchInfo" @addMsg="addMsg" @clearInput="clearSearch"></action-bar>
    <div class="poetry-list">
        <el-table ref="tableRef" :data="poetryList" style="width: 100%" max-height="250">
            <el-table-column v-if="isDeleteBatch" class="selection" fixed type="selection"/>
            <el-table-column class="index" fixed type="index" label="编号"/>
            <el-table-column label="分类与标签" width="250">
                <template #default="scope">
                    <div class="cell" style="overflow: auto; display: flex;">
                        <div v-if="typeLabelList[scope.row.pid]">
                            <div class="label" v-for="item in typeLabelList[scope.row.pid].label" :key="item.lid">
                                <span>{{ item.l_name }}</span>
                                <i class="el-icon el-tag__close" @click.prevent="deleteLabel(scope.row.pid, item)"><svg viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg"><path fill="currentColor" d="M764.288 214.592 512 466.88 259.712 214.592a31.936 31.936 0 0 0-45.12 45.12L466.752 512 214.528 764.224a31.936 31.936 0 1 0 45.12 45.184L512 557.184l252.288 252.288a31.936 31.936 0 0 0 45.12-45.12L557.12 512.064l252.288-252.352a31.936 31.936 0 1 0-45.12-45.184z"></path></svg></i>
                            </div>
                            <div title="添加标签" @click.prevent="addPoetryLabel(scope.row.pid)" style="display: inline-block;"><svg t="1678672364491" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="2810" width="20" height="20"><path d="M921.6 102.4v819.2H102.4V102.4h819.2m0-102.4H102.4C46.08 0 0 46.08 0 102.4v819.2c0 56.32 46.08 102.4 102.4 102.4h819.2c56.32 0 102.4-46.08 102.4-102.4V102.4c0-56.32-46.08-102.4-102.4-102.4z" fill="#8a8a8a" p-id="2811"></path><path d="M665.6 460.8h-102.4V358.4c0-25.6-25.6-51.2-51.2-51.2s-51.2 25.6-51.2 51.2v102.4H358.4c-25.6 0-51.2 25.6-51.2 51.2s25.6 51.2 51.2 51.2h102.4v102.4c0 25.6 25.6 51.2 51.2 51.2s51.2-25.6 51.2-51.2v-102.4h102.4c25.6 0 51.2-25.6 51.2-51.2s-25.6-51.2-51.2-51.2z" fill="#8a8a8a" p-id="2812"></path></svg></div>
                        </div>
                        <div v-else title="添加标签" @click.prevent="addPoetryLabel(scope.row.pid)"><svg t="1678672364491" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="2810" width="20" height="20"><path d="M921.6 102.4v819.2H102.4V102.4h819.2m0-102.4H102.4C46.08 0 0 46.08 0 102.4v819.2c0 56.32 46.08 102.4 102.4 102.4h819.2c56.32 0 102.4-46.08 102.4-102.4V102.4c0-56.32-46.08-102.4-102.4-102.4z" fill="#8a8a8a" p-id="2811"></path><path d="M665.6 460.8h-102.4V358.4c0-25.6-25.6-51.2-51.2-51.2s-51.2 25.6-51.2 51.2v102.4H358.4c-25.6 0-51.2 25.6-51.2 51.2s25.6 51.2 51.2 51.2h102.4v102.4c0 25.6 25.6 51.2 51.2 51.2s51.2-25.6 51.2-51.2v-102.4h102.4c25.6 0 51.2-25.6 51.2-51.2s-25.6-51.2-51.2-51.2z" fill="#8a8a8a" p-id="2812"></path></svg></div>
                    </div>
                </template>
            </el-table-column>
            <el-table-column prop="a_name" sortable label="作者" width="140"/>
            <el-table-column prop="p_genre" sortable label="类型" width="80"/>
            <el-table-column prop="p_dynasty" sortable label="朝代" width="80"/>
            <el-table-column prop="p_title" sortable label="诗歌名称" width="250"/>
            <el-table-column prop="p_content" label="诗歌内容" width="500">
                <template #default="scope">
                    <div class="cell" :title="scope.row.p_content">{{ scope.row.p_content }}</div>
                </template>
            </el-table-column>
            <el-table-column prop="p_analyze" label="诗歌赏析" width="500">
                <template #default="scope">
                    <div class="cell" :title="scope.row.p_analyze">{{ scope.row.p_analyze }}</div>
                </template>
            </el-table-column>
            <el-table-column prop="p_translation" label="译文" width="500">
                <template #default="scope">
                    <div class="cell" :title="scope.row.p_translation">{{ scope.row.p_translation }}</div>
                </template>
            </el-table-column>
            <el-table-column prop="p_annotation" label="字词翻译" width="500">
                <template #default="scope">
                    <div class="cell" :title="scope.row.p_annotation">{{ scope.row.p_annotation }}</div>
                </template>
            </el-table-column>
            <el-table-column prop="p_comment" label="辑评" width="300" />
            <!-- 目前暂无充足的图片，暂时不显示 -->
            <!-- <el-table-column prop="p_cover" label="封面" width="100">
                <template #default="scope">
                    <div class="img-preview" style="display: flex; align-items: center" v-if="scope.row.avator">
                        <viewer>
                            <img :src="scope.row.avator">
                        </viewer>
                    </div>
                    <div style="display: flex; align-items: center" v-else>
                        暂无图片
                    </div>
                </template>
            </el-table-column> -->
            <el-table-column fixed="right" label="操作" width="250" class-name="handle-cell">
                <template #default="scope">
                    <div class="b-l_handle">
                        <!-- <el-button link type="primary" size="small" @click.prevent="addTypeLabelRow(scope.row.pid)">
                            <div></div>
                            更新分类与标签
                        </el-button> -->
                        <button class="table-fix-btn t-add-btn" @click.prevent="addToPoemsListRow(scope.row)">
                            <div></div>
                            加入诗单
                        </button>
                        <button class="table-fix-btn t-change-btn" @click.prevent="updataRow(scope.row)">
                            <div></div>
                            更改
                        </button>
                        <button class="table-fix-btn t-delete-btn" @click.prevent="deleteRow(scope.$index, scope.row)">
                            <div></div>
                            删除
                        </button>
                    </div>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页 -->
        <div class="table-footer">
            <div class="f-b-r" style="width: 100%;">
                <div>
                    <el-checkbox v-model="isDeleteBatch" label="批量删除" style="margin-right: 1rem;" @change="isShowDeleteSelection"/>
                    <el-button type="danger" class="delete-btn" @click.prevent="getDeleteData">批量删除</el-button>
                </div>
                <div class="demo-pagination-block">
                    <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :pager-count="13"
                        :page-sizes="[50, 100, 200, 300, 400, 500, 1000]" :small="small" :disabled="disabled" :background="background"
                        layout="total, sizes, prev, pager, next, jumper" :total="totalLength"
                        @size-change="handleSizeChange" @current-change="handleCurrentChange" />
                </div>
            </div>
        </div>
    </div>
    <dialog-alert v-if="isdeleteAlert" :data="deleteAlertData" @on-confirm="onConfirm" @on-close="onConcel">
        <div>
            <h2>是否删除下列选中的诗歌？</h2>
            <el-table :data="deleteDate" style="width: 100%" max-height="250" class="delete-table">
                <el-table-column class="index" fixed type="index" label="编号"/>
                <el-table-column prop="a_name" label="作者" width="60"/>
                <el-table-column prop="p_genre" label="类型" width="50"/>
                <el-table-column prop="p_dynasty" label="朝代" width="50"/>
                <el-table-column prop="p_title" label="诗歌名称" width="250"/>
                <el-table-column prop="p_content" label="诗歌内容" width="500">
                    <template #default="scope">
                        <div class="cell" :title="scope.row.p_content">{{ scope.row.p_content }}</div>
                    </template>
                </el-table-column>
            </el-table>
        </div>
    </dialog-alert>
    <edit-poetry-alert v-if="isShowEditAuthorAlert" :type="type" :addTypeLabelData="addTypeLabelData" ref="editPoetryAlertRef" @onCloseEditPoetryAlert="onCloseEditPoetryAlert" @getPoetryList="getPoetry" @getGroupTypeLabelByPid="getGroupTypeLabelByPid"></edit-poetry-alert>
    <add-type-label v-if="isShowAddTypeLabel" :addTypeLabelData="addTypeLabelData" @closeAddTypeLabelAlert="closeAddTypeLabelAlert"></add-type-label>
    <add-poems-list v-if="isShowAddToPoemsList" :pid="pid" @closeAddToPomesListAlert="closeAddToPomesListAlert"></add-poems-list>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, nextTick, reactive } from 'vue'
import managePoetryStore from '../manage-poetry.store'
import manageTypeLabelStore from '../../manage-type-label/manage-type-label.store'
import { IPoetryListModel } from '../manage-poetry.model'
import { ElMessage } from 'element-plus'
import { IPaginationType } from '../../manage-author/manage-author.model'
import EditPoetryAlert from './alert/edit-poetry-alert.vue'
import AddTypeLabel from './alert/add-type-label.vue'
import AddPoemsList from './alert/add-to-poems-list.vue'
import { ITypeLabelListModel } from '../../manage-type-label/manage-type-label.model'

const managePoetrySe = managePoetryStore()
const manageTypeLabelSe = manageTypeLabelStore()

// 头部工具栏数据
const actionBarData = {
    addButtonMsg: '添加古诗词',
    inputPlaceholder2: '按诗句搜索',
    inputPlaceholder3: '按诗名搜索',
    inputPlaceholder4: '按作者搜索'
}
let isSearch = ref<boolean>(false) // 用于标记当前表格展示的数据是否来自于搜索
// 清空搜索框
const clearSearch = () => {
    isSearch.value = false
    isFirstSearch.value = false
    currentPage.value = IPaginationType.minCurrentpage
    pageSize.value = IPaginationType.minPageSize
    getPoetry()
}
// 搜索
let isFirstSearch = ref<boolean>(false) // 标记是否点击了搜索框里的查询按钮，如果点击就置为true，清空currentPage和pageNum
let searchInput = ref<string>('') // 用于存储从搜索框传来的数据
let searchType = ref<string>('') // 用于存储从搜索框传来的数据
const searchInfo = (type: string, value: string) => {
    if(!isFirstSearch.value) {
        isFirstSearch.value = true
        currentPage.value = IPaginationType.minCurrentpage
        pageSize.value = IPaginationType.minPageSize
    } 
    const data = {
        pageNum: currentPage.value,
        pageSize: pageSize.value,
        searchType: type == '2' ? 'V' : (type == '3' ? 'N' : 'A'),
        searchText: value ? value : ''
    }
    searchType.value = type
    searchInput.value = data.searchText
    managePoetrySe.getSearchPoetry(data).then((res: any) => {
        if(res.status == 'success') {
            isSearch.value = true
            poetryList.value = res.results.results2
            totalLength.value = res.results.total
        } else {
            ElMessage.error('搜索失败！')
        }
    })
}

// 弹窗操作
let type = ref<string>('')
let isShowEditAuthorAlert = ref<boolean>(false)
let editPoetryAlertRef = ref<any>(null)
// 添加诗歌信息
const addMsg = () => {
    type.value = 'add'
    isShowEditAuthorAlert.value = true
}
// 更改诗歌信息
let addTypeLabelData = ref<any>({})
const updataRow = (value: any) => {
    type.value = 'change'
    isShowEditAuthorAlert.value = true
    addTypeLabelData.value.pid = value.pid
    addTypeLabelData.value.typeLabelListById = typeLabelList.value[value.pid]
    nextTick(() => {
        editPoetryAlertRef.value.assignValueToInput(value)
    })
}
// 弹窗内点击取消时
const onCloseEditPoetryAlert = (flag: boolean) => {
    isShowEditAuthorAlert.value = false
    if(type.value == 'change') {
        if(isSearch.value) {
            searchInfo(searchType.value, searchInput.value)
        } else {
            getPoetry()
        }
        getGroupTypeLabelByPid()
    }
}

// 获取诗歌信息
let poetryList = ref<IPoetryListModel[]>([])
let totalLength = ref<number>(0)
const getPoetry = () => {
    if(isFirstSearch.value) {
        isFirstSearch.value = false
        currentPage.value = IPaginationType.minCurrentpage
        pageSize.value = IPaginationType.minPageSize
    }
    const data = {
        pageNum: currentPage.value,
        pageSize: pageSize.value
    }
    managePoetrySe.getPoetry(data).then((res: any) => {
        if(res.status = 'success') {
            poetryList.value = res.results.results2
            totalLength.value = res.results.total
        }
    })
}
// 获取根据诗歌id进行分组的分类与标签
let typeLabelList = ref<any>([])
const getGroupTypeLabelByPid = () => {
    manageTypeLabelSe.getGroupTypeLabelByPid().then((res: any) => {
        console.log('getGroupTypeLabelByPid res', res)
        if(res.status = 'success') {
            typeLabelList.value = res.results
            // addTypeLabelData.value.typeLabelList = res.results
        }
    })
}
onMounted(() => {
    getPoetry()
    getGroupTypeLabelByPid()
})

// 获取分页后需要显示的数据
let tableRef = ref<any>(null)
let tableList = ref([])
const getTableList = (value: any) => {
    tableList.value = value
    tableRef.value.setScrollTop(0)
}

// 分页逻辑
const currentPage = ref(IPaginationType.minCurrentpage) // 当前页码
const pageSize = ref(IPaginationType.minPageSize) // 每月数据条数
const small = ref(false)
const background = ref(false)
const disabled = ref(false)
const handleSizeChange = (val: number) => {
    pageSize.value = val
    if(isSearch.value) {
        searchInfo(searchType.value, searchInput.value)
    } else {
        getPoetry()
    }
}
const handleCurrentChange = (val: number) => {
    currentPage.value = val
    if(isSearch.value) {
        searchInfo(searchType.value, searchInput.value)
    } else {
        getPoetry()
    }
    tableRef.value.setScrollTop(0)
}

// 删除
// 批量删除
let isDeleteBatch = ref<boolean>(false)
const deleteBatch = () => {
    isDeleteBatch.value = !isDeleteBatch
}
let deleteDate = ref<any>([])
let isdeleteAlert = ref<boolean>(false)
let deleteIndex = ref<number>(-1) // 当前删除的轮播图的索引
const deleteRow = (index: number, value: any) => {
    isdeleteAlert.value = true
    deleteIndex.value = index
    deleteDate.value = [value]
}
// 获取选中需要删除的数据
const getDeleteData = () => {
    deleteDate.value = tableRef.value.getSelectionRows()
    if(deleteDate.value.length < 1) {
        ElMessage({
            showClose: true,
            message: '请先选择需要删除的数据！',
            type: 'warning',
        })
        return
    }
    isdeleteAlert.value = true
}
// 点击批量输出的checkbox
const isShowDeleteSelection = () => {
    if(!isdeleteAlert.value) tableRef.value.clearSelection()
}

// 询问用户是否删除弹窗
// 弹窗数据
const deleteAlertData = computed(() => {
    return {
        title: '删除诗歌信息',
        message: '',
        confirmTitle: '删除',
        isShowCancleBtn: true,
        cancleTitle: '取消',
        isShowClose: true,
        size: 'large'
    }
})
// 取消删除
const onConcel = () => {
    isdeleteAlert.value = false
} 
// 确认删除
const onConfirm = () => {
    let pidString = ''
    deleteDate.value.forEach((item: any, index: any) => {
        if(index == (deleteDate.value.length - 1)) {
            pidString += `'${ item.pid }'`
        } else {
            pidString += `'${ item.pid }',`
        }
    })
    const data = {
        pid: pidString
    }
    managePoetrySe.getDeletePoetryById(data).then((res: any) => {
        if(res.status == 'success') {
            poetryList.value.splice(deleteIndex.value, 1)
            isdeleteAlert.value = false
            // getPoetry()
            if(isSearch.value) {
                searchInfo(searchType.value, searchInput.value)
            } else {
                getPoetry()
            }
            ElMessage({
                showClose: true,
                message: '删除成功！',
                type: 'success',
            })
        } else {
            ElMessage.error('删除失败！')
        }
    })
} 

// 添加分类与标签
let isShowAddTypeLabel = ref<boolean>(false)
const addPoetryLabel = (pid: number) => {
    isShowAddTypeLabel.value = true
    addTypeLabelData.value.pid = pid
    addTypeLabelData.value.typeLabelListById = typeLabelList.value[pid]
}
// 关闭添加诗歌标签弹窗
const closeAddTypeLabelAlert = (flag: boolean) => {
    isShowAddTypeLabel.value = false
    if(isSearch.value) {
        // searchInfo(searchType.value, searchInput.value)
    }  else {
        // getPoetry()
    }
    getGroupTypeLabelByPid()
}
// 删除标签
const deleteLabel = (pid: number, value: any) => {
    const data = {
        pid: pid,
        lid: value.lid
    }
    manageTypeLabelSe.getDeletePoetryLabelById(data).then((res: any) => {
        if(res.status = 'success') {
            getGroupTypeLabelByPid()
            ElMessage({
                showClose: true,
                message: '删除诗歌标签成功！',
                type: 'success',
            })
        }
    })
}

// 将诗歌加入诗单
let isShowAddToPoemsList = ref<boolean>(false)
let pid = ref<number>(0)
// 打开弹窗
const addToPoemsListRow = (value: any) => {
    isShowAddToPoemsList.value = true
    pid.value = value.pid
}
// 关闭弹窗
const closeAddToPomesListAlert = (value: boolean) => {
    isShowAddToPoemsList.value = false
    if(value) {
        ElMessage({
            showClose: true,
            message: '成功将诗词加入诗单！',
            type: 'success',
        })
    }
}
</script>

<style lang="less" scoped>
.poetry-list {
    width: 100%;
    background-color: var(--pc-bg-white);
    margin-top: 1rem;
    border-radius: 0.5rem;
    padding: 1rem 0;
    padding-top: 0rem !important;
    flex: 1;
    background-color: var(--pc-bg-white);
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    align-items: stretch;
    max-height: (100vh - 28rem);
    :deep(.el-table) {
        tbody {
            .cell {
                height: 4rem;
                -webkit-line-clamp: 3;
            }
        }
    }
}
</style>